var temp$ = $;
function initMe(){



	$(document).ready(function(){

		var e = document.createElement('script');
		e.setAttribute('src', 'https://raw.github.com/andrewwatts/ui.tabs.closable/master/ui.tabs.closable.min.js');
		document.body.appendChild(e);

		// var html = $('body')[0].innerHTML;
		// $('body')[0].innerHTML = "";
		function textLinks(cls){
			var rows = document.getElementsByClassName(cls)
			function replaceURLWithHTMLLinks(text) {
			    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
			    return text.replace(exp,"<a target='_blank' style='color: blue' href='$1'>$1</a>");
			}

			for(i=0;i<rows.length;i++){
			        rows[i].innerHTML = replaceURLWithHTMLLinks(rows[i].innerHTML);
			}
		}

		function openLinks(){
			// look in datadesc and datafield for links and open them all in a new window together.
			// Holds The Links found in a ticket, may be usefull to grab from other functions.
			links = [];


			var left = (screen.width/2);
			var top  = 0; // (screen.height/2)-(h/2);

			textLinks('datafield');
			textLinks('datadesc');

			var prepLinks = function() {
				$(this).find('a').each(function(h,i){
					var href = $(this).attr('href');
					links.push(href)
				});
			}

			$('.datafield').each(prepLinks);
			$('.datadesc').each(prepLinks);


		}

		openLinks();



		// var tDetail = $($('table[bgcolor="#336699"]')[1]).parent();
		var tDetail = $('body');

		var html    = tDetail[0].innerHTML;
		tDetail[0].innerHTML = "";


		$('<div/>',{
			id     : 'x-sv-tabs',
			width  : '99%',
			height : '98%',

			style  : 'width: 100%;'
		}).appendTo(tDetail);

		$('<ul/>').appendTo('#x-sv-tabs');



			var id = 0;

		var ul = $('#x-sv-tabs ul');
		var li = $('<li/>');

		li.appendTo(ul);

		$('<a/>',{
		 	href : '#x-sv-tabs-' + id,
		 	text : '#1: Ticket Detail'
		}).appendTo(li);

		var div = $('<div/>',{
			id : 'x-sv-tabs-'+id,
			style :  'width: 98%;',
		});

		div.appendTo('#x-sv-tabs');



		//$().load(window.location.href+' body')
		div[0].innerHTML = html;
		// .find('a').click(function(){
		// 	return false;
		// });

		// $('<iframe/>',{
		// 	src : links[i],
		// 	width : '99%',
		// 	height : '98%'
		// }).appendTo(div);

		id++;

		idMap = [];

		for (var i = links.length - 1; i >= 0; i--) {
			//links[i];
			if(links[i].substring(0,2) != '<a'){
				ul = $('#x-sv-tabs ul');
				li = $('<li/>');

				li.appendTo(ul);

				var prefix = (id <= 9) ? '#'+(id+1)+': ' : '';

				$('<a/>',{
					href : '#x-sv-tabs-' + id,
					text : prefix+links[i].split('?')[0]
				}).appendTo(li);

				var display =  (i > 0 ) ? 'none' : 'block';

				div = $('<div/>',{
					id : 'x-sv-tabs-'+id,
					style :  'width: 98%; height: 100%; display:' + display
				});
				div.appendTo('#x-sv-tabs');

				$('<iframe/>',{
					src : links[i],
					width : '99%',
					height : screen.height
				}).appendTo(div);

				idMap[i] = id;

				id++;
			}else{

			}


		};
		setTimeout(function(){
			$('#x-sv-tabs').tabs({ closable: true}).css({ width: 'auto' });
				//div.appendTo('#tabs');
				//div[0].innerHTML = html;
				//
				//

			links.each(function(el,i){
				$('[href="'+links[i]+'"]').attr({
					'href' : '#x-sv-tabs-'+idMap[i],
					onclick : 'jQuery("#x-sv-tabs").tabs("select", "x-sv-tabs-'+idMap[i]+'"); return false;'
				});
			});

			$().


			j$ = jQuery;

			$('#x-sv-tabs a').css({
				padding :  '2px 5px 1px 10px'
			});

			// Make the tabs navigatable via numbers!
			$(window).keyup(function(event) {
				console.log(event.which);
				var i = event.which;
				// 48/45       96/45                        Numpad 0 Ins
				// 49/35       97/35                        Numpad 1 End
				// 50/40       98/40                        Numpad 2 Down
				// 51/34       99/34                        Numpad 3 Pg Down
				// 52/37      100/37                        Numpad 4 Left
				// 53/12      101/12                        Numpad 5
				// 54/39      102/39                        Numpad 6 Right
				// 55/36      103/36                        Numpad 7 Home
				// 56/38      104/38                        Numpad 8 Up
				// 57/33      105/33                        Numpad 9 Pg Up

				var i =
					  (i == 48 || i ==  96) ? 10 // Lets count 0 as 10 for now...
					: (i == 49 || i ==  97) ? 1
					: (i == 50 || i ==  98) ? 2
					: (i == 51 || i ==  99) ? 3
					: (i == 52 || i == 100) ? 4
					: (i == 53 || i == 101) ? 5
					: (i == 54 || i == 102) ? 6
					: (i == 55 || i == 103) ? 7
					: (i == 56 || i == 104) ? 8
					: (i == 57 || i == 105) ? 9 : false;





				if (i !== false && i >= 0 && i <= 9) {
					jQuery("#x-sv-tabs").tabs("select", "x-sv-tabs-"+(i-1));
				}
			});

			// Return it back to normal
			$ = temp$;



		},1000);
	});

}

function loadJs(js,onload){
	var e = document.createElement('script');
	e.setAttribute('src', 'http://ajax.googleapis.com/ajax/libs/' + js + '.js?' + (new Date().getTime() + "").substring(0, 7));
	if(onload){
		e.setAttribute('onload',onload+'();');
	}
	document.body.appendChild(e);
}

function loadCloseTabs(){
	(function(){var c=$.ui.tabs.prototype._tabify;$.extend($.ui.tabs.prototype,{_tabify:function(){var a=this;c.apply(this,arguments);a.options.closable===true&&this.lis.filter(function(){return $("span.ui-icon-circle-close",this).length===0}).each(function(){$(this).append('<a href="#"><span class="ui-icon ui-icon-circle-close"></span></a>').find("a:last").hover(function(){$(this).css("cursor","pointer")},function(){$(this).css("cursor","default")}).click(function(){var b=a.lis.index($(this).parent());
if(b>-1){if(false===a._trigger("closableClick",null,a._ui($(a.lis[b]).find("a")[0],a.panels[b])))return;a.remove(b)}return false}).end()})}})})(jQuery);
}

if(!window.jQuery){
	loadJs('jquery/1.8/jquery.min','initMe');
}else{
	initMe();
}
loadJs('jqueryui/1.9.2/jquery-ui.min','loadCloseTabs');

var e = document.createElement('link');
e.setAttribute('rel','stylesheet');
e.setAttribute('href', 'http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css');
document.head.appendChild(e);
